<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use App\Facades\Response;
use Symfony\Component\HttpFoundation\Response as FoundationResponse;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    /**
     * 成功消息
     * @param $message
     * @param $data
     * @return mixed
     */
    public function success($message = '操作成功', $data = null)
    {
        return $this->message($message, $data, 0);
    }

    /**
     * 返回数据
     * @param $data
     * @param string $message
     * @return mixed
     */
    public function successData($data, $message = '成功')
    {
        return $this->message($message, $data, 0);
    }

    /**
     * 返回数据 根据数据来确定是返回成功还是失败
     * @param $data
     * @param string $message
     * @return mixed
     */
    public function response($data, $message = '')
    {
        if ($data instanceof \Illuminate\Support\Collection) {
            $data = $data->toArray();
        }
        if ($data) {
            return $this->successData($data, $message ?: '成功');
        }
        return $this->message($message ?: '失败', $data);
    }


    /**
     * 一般消息
     * @param $message
     * @param $data
     * @param int $errorCode
     * @param int $statusCode
     * @return mixed
     */
    public function message($message = '', $data = null, $errorCode = 1, $statusCode = FoundationResponse::HTTP_OK)
    {
        return Response::message($message, $data, $errorCode, $statusCode);
    }


    /**
     * 参数验证器
     * @param $request
     * @param array $rules
     * @param string $msg
     * @return array
     */
    public function validate($request, array $rules, $msg = '参数错误')
    {
        if (is_array($request)) {
            $data = $request;
        } else {
            $data = $request->all();
        }
        $valid = validator($data, $rules);
        if ($valid->fails()) {
            $errors = $valid->errors()->all();
            abort(400, json_encode(['errors' => $errors, 'msg' => $msg]));
        }
        return $data;
    }


}
